import { constantRouterMap, asyncRouterMap } from "@/router"

//判断是否有权限访问该菜单
function hasPermission(menus, route) {
    if (route.name) {
        let currMenu = getMenu(route.name, menus);
        if (currMenu != null) {
            //设置菜单的标题、图标和可见性
            if (currMenu.title != null && currMenu.title !== '') {
                route.meta.title = currMenu.title;
            }
            if (currMenu.icon != null && currMenu.title !== '') {
                route.meta.icon = currMenu.icon;
            }
            if (currMenu.hidden != null) {
                route.hidden = currMenu.hidden == 0 ? false : true;
            }
            if (currMenu.sort != null && currMenu.sort !== '') {
                route.sort = currMenu.sort;
            }
            return true;
        } else {
            route.sort = 0;
            if (route.hidden !== undefined && route.hidden === true) {
                route.sort = -1;
                return true;
            } else {
                return false;
            }
        }
    } else {
        return true
    }
}

//根据路由名称获取菜单
function getMenu(name, menus) {
    for (let i = 0; i < menus.length; i++) {
        let menu = menus[i];
        if (name === menu.name) {
            return menu;
        }
    }
    return null;
}

//对菜单进行排序
function sortRouters(accessedRouters) {
    for (let i = 0; i < accessedRouters.length; i++) {
        let router = accessedRouters[i];
        if (router.children && router.children.length > 0) {
            router.children.sort(compare("sort"));
        }
    }
    accessedRouters.sort(compare("sort"));
}

//降序比较函数
function compare(p) {
    return function (m, n) {
        let a = m[p];
        let b = n[p];
        return b - a;
    }
}

// state：仓库存储数据的地方
const state = {
    // 是否展示菜单栏 
    isCollapse: false,
    // 菜单栏信息
    menuInfo: [],
    // 路由
    routers: constantRouterMap,
    // 新增的路由
    addRouters: [],
    // 传入的后端菜单
    menuList: [],
    // 父菜单
    parentMenu: [],
    // 历史导航
    navHistory: [
        {
            path: "/dashboard",
            meta: {
                title: "桌面",
            }
        }
    ],
    // 用户菜单
    userMenuList: []

}
// mutations：修改state的唯一手段，因此第一个参数必须是state，第二个参数为将要修改的数据
const mutations = {
    changeShow(state, res) {
        state.isCollapse = res
    },
    setRouters(state, res) {
        state.addRouters = res
        state.routers = constantRouterMap.concat(res)
    },
    setMenuInfo(state, res) {
        state.menuInfo = res
    },
    setMenuList(state, menuList) {
        state.menuList = menuList
    },
    setParentMenu(state, parentMenu) {
        state.parentMenu = parentMenu;
    },
    saveNavHistory(state, res) {
        let flag = false;
        state.navHistory.forEach(item => {
            if (item.path == res.path) flag = true;
        });
        if (!flag) state.navHistory.push(res)
    },
    setUserMenu(state, res) {
        state.userMenuList = res;
    },
}
// action：书写业务逻辑（method方法）
const actions = {
    // 折叠或展开
    changeShow({ commit }, data) {
        commit('changeShow', data)
    },
    GenerateRoutes({ commit }, data) {
        return new Promise(resolve => {
            const { menus } = data;
            const accessedRouters = asyncRouterMap.filter(v => {
                // admin帐号直接返回所有菜单
                // if(username==='admin') return true;
                if (hasPermission(menus, v)) {
                    if (v.children && v.children.length > 0) {
                        v.children = v.children.filter(child => {
                            if (hasPermission(menus, child)) {
                                return child
                            }
                            return false;
                        });
                        return v
                    } else {
                        return v
                    }
                }
                return false;
            });
            //对菜单进行排序
            sortRouters(accessedRouters);
            commit('setRouters', accessedRouters);
            resolve();
        })
    },


}
// getters：计算属性
const getters = {

}

export default {
    state,
    mutations,
    actions,
    getters
}